<?php

declare(strict_types=1);

namespace app\common\AliYunOss;

//阿里云OSS文件上传类
use OSS\OssClient;
use OSS\Core\OssException;
use app\common\AliYunOss\Common;
use think\facade\Log;

class Image
{
    private $ossClient;
    private $bucketName;

    public function __construct()
    {
        $this->ossClient = Common::getOssClientInstance();
        $this->bucketName = Common::getBucketName();
    }


    /**
     * @describe 上传文件到OSS（Object Storage Service）。 如果上传成功，将返回包含文件URL的数组；如果上传失败，则返回包含错误信息的数组
     * @author: Bobo
     * @date: 2024-06-07 15:10:34 
     * @param $ossPath [str] @required 文件在OSS中的目标路径
     * @param $filePath [str] @required 本地文件的路径
     * @return bool 上传结果
     * @throws OssException 如果上传过程中出现OSS相关的异常。
     */
    public function uploadFile($ossPath, $filePath)
    {
        try {
            $this->ossClient->uploadFile($this->bucketName, $ossPath, $filePath);
            return true;
        } catch (OssException $e) {
            Log::error("AliYunOss failed to upload files, error message:" . $e->getMessage());
            return false;
        }
    }

    public function deleteFile($ossPath)
    {
        try {
            $this->ossClient->deleteObject($this->bucketName, $ossPath);
            return true;
        } catch (OssException $e) {
            return false;
        }
    }
}
